package dao

import (
	"context"
	"device-admin/internal/dal"
	"device-admin/internal/models"
	"strings"

	"192.168.1.75/go-pkg/errorx"
)

type Location struct{}

// Exists 位置是否存在
func (Location) Exists(ctx context.Context, query *dal.Query, locationID string) bool {
	l := query.Location
	count, err := l.WithContext(ctx).Where(l.ID.Eq(locationID)).Count()
	if err != nil || count <= 0 {
		return false
	}
	return true
}

// LocationNameMap 获取位置名称
func (Location) LocationNameMap(ctx context.Context, locationIDs []string) map[string]string {
	idNameMap := make(map[string]string)
	l := dal.Location
	lx := l.WithContext(ctx)
	records, err := lx.Where(l.ID.In(locationIDs...)).Find()
	if err != nil {
		return nil
	}
	for _, record := range records {
		idNameMap[record.ID] = record.Name
	}
	return idNameMap
}

// Detail 位置详情
func (Location) Detail(
	ctx context.Context,
	query *dal.Query,
	locationID string,
) (*models.Location, error) {
	l := query.Location
	tx := l.WithContext(ctx)
	if locationID == "" {
		return nil, errorx.New("位置id不能为空", -1)
	}
	return tx.Where(l.ID.Eq(locationID)).Take()
}

// List 位置列表
func (Location) List(
	ctx context.Context,
	query *dal.Query,
	provinceID, cityID, districtID string, // 省市区
	page, limit int, // 分页参数
) (records []*models.Location, total int64, err error) {
	l := query.Location
	tx := l.WithContext(ctx)
	if provinceID != "" {
		tx = tx.Where(l.ProvinceID.In(strings.Split(provinceID, ",")...))
	}
	if cityID != "" {
		tx = tx.Where(l.CityID.In(strings.Split(cityID, ",")...))
	}
	if districtID != "" {
		tx = tx.Where(l.DistrictID.In(strings.Split(districtID, ",")...))
	}
	total, _ = tx.Count()
	records, err = tx.Offset(GetPageOffset(page, limit)).
		Limit(GetPageLimit(limit)).
		Find()
	return records, total, err
}
